<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇重点在于了解 String 类型也具有基本包装类型的特性，其次便是掌握 String 对象常用的实例方法。">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第五章：String">
<meta property="og:url" content="http://yoursite.com/2019/05/05/professional-javascript-chapter-5-String/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇重点在于了解 String 类型也具有基本包装类型的特性，其次便是掌握 String 对象常用的实例方法。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/05/05/professional-javascript-chapter-5-String/javascript.jpg">
<meta property="og:updated_time" content="2019-05-04T14:08:33.128Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第五章：String">
<meta name="twitter:description" content="本篇重点在于了解 String 类型也具有基本包装类型的特性，其次便是掌握 String 对象常用的实例方法。">
<meta name="twitter:image" content="http://yoursite.com/2019/05/05/professional-javascript-chapter-5-String/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/05/05/professional-javascript-chapter-5-String/">





  <title>《JavaScript 高级程序设计》第五章：String | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/05/05/professional-javascript-chapter-5-String/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第五章：String</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-05T06:04:04+08:00">
                2019-05-04
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2019/05/05/professional-javascript-chapter-5-String/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇重点在于了解 <code>String</code> 类型也具有基本包装类型的特性，其次便是掌握 <code>String</code> 对象常用的实例方法。</blockquote>

<a id="more"></a>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p><code>String</code> 对象是对应基本类型“字符串”的引用类型。<br><code>String</code> 类型与 <code>Number</code>、<code>Boolean</code> 类型都属于“基本包装类型”。<br><code>String</code> 类型也具有数组的某些特征，例如 <code>length</code> 属性，可以返回字符串中字符的个数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sayHello = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'hello world'</span>);</span><br><span class="line">sayHello.length; <span class="comment">//11</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>PS: <code>String</code> 的 <code>length</code> 属性只能统计字符串中的字符个数，但是并不能区分该字符是单字节字符还是多字节字符。  </p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'您好，世界！'</span>.length <span class="comment">//6</span></span><br></pre></td></tr></table></figure>
<p><code>String</code> 对象与数组一样，也支持通过下标来访问某个字符：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sayHello[<span class="number">0</span>]; <span class="comment">//'h'</span></span><br><span class="line">sayHello[<span class="number">1</span>]; <span class="comment">//'e'</span></span><br></pre></td></tr></table></figure>
<h2 id="转换方法"><a href="#转换方法" class="headerlink" title="转换方法"></a>转换方法</h2><p><code>String</code> 对象也具有 <code>toString()</code>、<code>toLocaleString()</code>、<code>valueOf()</code> 等转换方法，它们都返回 <code>String</code> 对象对应的基本类型字符串值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'String'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">typeof</span> str; <span class="comment">//"object"</span></span><br><span class="line"><span class="keyword">typeof</span> str.toString(); <span class="comment">//"string"</span></span><br><span class="line"><span class="keyword">typeof</span> str.toLocaleString(); <span class="comment">//"string"</span></span><br><span class="line"><span class="keyword">typeof</span> str.valueOf(); <span class="comment">//"string"</span></span><br></pre></td></tr></table></figure>
<h2 id="String"><a href="#String" class="headerlink" title="String()"></a>String()</h2><p><code>String()</code> 既是“构造函数”也可以是一个普通的函数(将构造函数充当普通函数调用)。其功能是将其它类型的数据转换为对应的“字符”型结果。<br>作为“构造函数”它会把传入的参数按照 ECMA 规范转换为对应的字符串并返回一个 <code>String</code> 类型的实例对象，而作为“转换方法”则只会根据规范将参数转换为对应“基本类型”的字符串然后返回。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> stringObject = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="literal">undefined</span>);<span class="comment">//String &#123;"undefined"&#125;</span></span><br><span class="line"><span class="keyword">var</span> string = <span class="built_in">String</span>(<span class="literal">null</span>); <span class="comment">//"null"</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>关于 <code>String()</code> 转换方法将其它类型数据转换为字符串的具体规则，请参考第三章。</p>
</blockquote>
<h2 id="实例方法"><a href="#实例方法" class="headerlink" title="实例方法"></a>实例方法</h2><p>“实例方法” 指的是 <code>String</code> 对象构造函数原型(prototype)对象上定义的方法，可以被其实例对象所继承。</p>
<h3 id="字符与编码"><a href="#字符与编码" class="headerlink" title="字符与编码"></a>字符与编码</h3><ul>
<li>charAt() / charCodeAt()</li>
</ul>
<p><code>charAt</code> 与 <code>charCodeAt</code> 方法都接收一个位置（数值）作为参数，然后以单字节的形式返回字符串中指定位置的字符。它们的区别在于前者返回的是字符本身，而后者返回的是字符所对应的编码（十进制形式）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'string'</span>);</span><br><span class="line"><span class="keyword">var</span> name = <span class="string">'我'</span>;</span><br><span class="line"></span><br><span class="line">str.charAt(<span class="number">0</span>); <span class="comment">//s</span></span><br><span class="line">str.charCodeAt(<span class="number">1</span>); <span class="comment">//116</span></span><br><span class="line"></span><br><span class="line">name.charAt() <span class="comment">//我</span></span><br><span class="line">name.charCodeAt() <span class="comment">//25105</span></span><br></pre></td></tr></table></figure>
<h3 id="字符串操作"><a href="#字符串操作" class="headerlink" title="字符串操作"></a>字符串操作</h3><ul>
<li>concat()</li>
</ul>
<p><code>concat()</code> 方法可以接收多个字符串参数，并将所有参数都拼接成一个完整的字符串。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'h'</span>);</span><br><span class="line">str.concat(<span class="string">'e'</span>, <span class="string">'l'</span>, <span class="string">'l'</span>, <span class="string">'o'</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>toLowerCase() / toUpperCase()</li>
</ul>
<p>字符串的大小写转换。<code>toLowerCase</code> 转换为小写，<code>toUpperCase</code> 转换为大写。</p>
<ul>
<li>trim()</li>
</ul>
<p><code>trim</code> 方法是 ES5 新增的方法。<br><code>trim</code> 方法用于清除两端空格。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">' a b c '</span>);</span><br><span class="line">str.trim(); <span class="comment">//'a b c'</span></span><br></pre></td></tr></table></figure>
<h3 id="字符串截取"><a href="#字符串截取" class="headerlink" title="字符串截取"></a>字符串截取</h3><ul>
<li>slice() / substr() / substring()</li>
</ul>
<p>这三个方法都会从原字符串的指定范围内截取并返回一个子串。<br>它们都接收一到两个参数，第一个参数是截取的起始位置，而第二个参数则是截取的结束位置（不包含最后一个字符），如果第二个参数缺省，则默认为截取到整个字符串的尾部。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'hello world'</span>;</span><br><span class="line"></span><br><span class="line">str.slice(<span class="number">0</span>, <span class="number">1</span>); <span class="comment">//"h"</span></span><br><span class="line">str.slice(<span class="number">3</span>);  <span class="comment">//"lo world"</span></span><br><span class="line">str.substring(<span class="number">0</span>, <span class="number">1</span>);  <span class="comment">//"h"</span></span><br><span class="line">str.substring(<span class="number">3</span>); <span class="comment">//"lo world"</span></span><br></pre></td></tr></table></figure>
<p>另外 <code>slice</code> 方法还可以接受负数作为参数，如果为负数，那么真正的值则是整个字符串的长度 <code>length</code> 加上这个负数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'abcd'</span>;</span><br><span class="line"></span><br><span class="line">str.length; <span class="comment">//4</span></span><br><span class="line">str.slice(<span class="number">-1</span>); <span class="comment">//d =&gt; str.slice(-1+4=3)</span></span><br><span class="line">str.slice(<span class="number">-2</span>, <span class="number">-1</span>); <span class="comment">//c =&gt; str.slice(-2+4=2,-1+4=3);</span></span><br></pre></td></tr></table></figure>
<p>而第二个参数对于 <code>substr</code> 方法要较为特殊，此时不再是截取的结束位置，而是要截取的字符数量。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str.substr(<span class="number">3</span>, <span class="number">2</span>); <span class="comment">//"lo"</span></span><br><span class="line">str.substr(<span class="number">3</span>); <span class="comment">//"lo world"</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>如果缺省 <code>substr</code> 方法的最后一个参数，默认也是截取到最后一个字符。</p>
</blockquote>
<h3 id="字符串位置"><a href="#字符串位置" class="headerlink" title="字符串位置"></a>字符串位置</h3><ul>
<li>lastIndexOf() / indexOf()</li>
</ul>
<p><code>lastIndexOf</code> 方法与 <code>indexOf</code> 方法都可以从一个字符串中查找给定的字符或子串，如果查找到，则返回这个字符或子串在原字符串中的(首字符)索引位置，否则返回 <code>-1</code>。它们的区别则是前者从字符串开头位置向后查找，而后者则是完全相反的方向。 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'hellow world'</span>);</span><br><span class="line">str.indexOf(<span class="string">'e'</span>); <span class="comment">//1;</span></span><br></pre></td></tr></table></figure>
<p>另外，这两个方法还可以接受第二个参数，用来指定查找的起始位置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str.indexOf(<span class="string">'e'</span>,<span class="number">2</span>); <span class="comment">//-1</span></span><br><span class="line">str.lastIndexOf(<span class="string">'e'</span>, <span class="number">0</span>); <span class="comment">//-1</span></span><br></pre></td></tr></table></figure>
<p>利用字符串的位置方法，我们可以从一段文本中筛选出指定字符或字串出现的次数与位置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> string = <span class="string">'Good love makes you see the whole world from one person while bad love makes you abandon the whole world for one person.'</span>;</span><br><span class="line"><span class="keyword">var</span> findChar = <span class="string">'love'</span>;</span><br><span class="line"><span class="keyword">var</span> posArr = [];</span><br><span class="line"><span class="keyword">var</span> pos = string.indexOf(findChar);</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> (pos != <span class="number">-1</span>) &#123;</span><br><span class="line">    posArr.push(pos);</span><br><span class="line">    pos = string.indexOf(findChar, pos + <span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="字符串模式匹配方法"><a href="#字符串模式匹配方法" class="headerlink" title="字符串模式匹配方法"></a>字符串模式匹配方法</h3><blockquote>
<p>字符串模式匹配方法可以与正则表达式结合使用。</p>
</blockquote>
<ul>
<li>search()</li>
</ul>
<p><code>search()</code> 方法与 <code>indexOf()</code> 方法非常相同，它们都会在一个字符串中查找给定的字符或子串，并返回位置值，如果没有查找到则返回 <code>-1</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'hello'</span>;</span><br><span class="line">str.search(<span class="string">'h'</span>); <span class="comment">//0</span></span><br></pre></td></tr></table></figure>
<p>区别则是 <code>search()</code> 方法只接受一个参数，既要查找的字符串或者是一个正则表达式对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str.search(<span class="regexp">/e/</span>); <span class="comment">//1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>match()</li>
</ul>
<p><code>match()</code> 方法的功能与返回值格式非常类似于 <code>RegExp</code> 对象中的 <code>exec()</code> 方法。<br><code>match(pattern)</code> 方法只接受一个参数，即要匹配的模式，这个匹配模式可以是一个普通的字符或子串，也可以是一个正则表达式对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'hellow'</span>;</span><br><span class="line">str.match(<span class="regexp">/(l)/</span>); <span class="comment">// ["l", "l", index: 2, input: "hellow"]</span></span><br><span class="line">str.match(<span class="regexp">/(k)/</span>); <span class="comment">// null</span></span><br></pre></td></tr></table></figure>
<p><code>match()</code> 方法的返回值是一个数组，数组中的第一个元素是匹配到的结果，而之后的数组元素则是每个分组匹配到的结果，<code>index</code> 的值表示匹配结果的首字符所在原字符串中的位置索引，而 <code>input</code> 则是返回原字符串本身，若没有匹配到任何结果，则返回 <code>null</code>。</p>
<p>总的来说 <code>match()</code> 返回值主要包括：“匹配结果”、“分组结果”、“结果索引”、“原字符串”。</p>
<ul>
<li>replace()</li>
</ul>
<p><code>replace()</code> 方法实现了字符串的替换操作，它接收两个参数，分别是“匹配模式”以及要替换的内容。“匹配模式”可以是一个字符串，也可以是一个正则对象。要替换的内容可以是一个字符串也可以是一个回调函数，然后由这个回调函数来返回要替换的内容。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'hellow'</span>;</span><br><span class="line">str.replace(<span class="string">'ellow'</span>,<span class="string">'i'</span>); <span class="comment">//"hi"</span></span><br><span class="line">str.replace(<span class="regexp">/e.+/</span>,<span class="string">'i'</span>); <span class="comment">//"hi"</span></span><br></pre></td></tr></table></figure>
<p>如果第二个参数（要替换的内容）是一个字符串，则还可以使用一些特殊的字符序列，将正则表达式的操作结果插入到结果字符串中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str.replace(<span class="regexp">/(e.+)/</span>,<span class="string">'(i|$1)'</span>); <span class="comment">//"h(i|ellow)"</span></span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th style="text-align:center">字符序列</th>
<th style="text-align:center">替换文本</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">$$</td>
<td style="text-align:center">$</td>
</tr>
<tr>
<td style="text-align:center">$&amp;</td>
<td style="text-align:center">匹配整个模式的子字符串。与RegExp.lastMatch的值相同</td>
</tr>
<tr>
<td style="text-align:center">$’</td>
<td style="text-align:center">匹配的子字符串之前的子字符串。与RegExp.leftContext的值相同</td>
</tr>
<tr>
<td style="text-align:center">$`</td>
<td style="text-align:center">匹配的子字符串之后的子字符串。与RegExp.rightContext的值相同</td>
</tr>
<tr>
<td style="text-align:center">$n[m]</td>
<td style="text-align:center">指定分组的匹配结果</td>
</tr>
</tbody>
</table>
<blockquote>
<p>关于这些“字符序列”我们可以等同理解为 <code>RegExp</code> 对象的静态属性，它作用在当前正则实例的执行上下文中。</p>
</blockquote>
<p>如果第二个参数是一个回调函数，那么这个函数可以接受三个参数，分别是匹配结果、结果首字符的索引位置以及原字符串。如果匹配模式是一个正则对象，且指定了全局修饰符 <code>g</code>，那么回调函数便会根据匹配结果的次数被多次调用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">htmlEscape</span>(<span class="params">text</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> text.replace(<span class="regexp">/[&lt;&gt;"&amp;]/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">result, resultIndex, originalText</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">switch</span> (result) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'&lt;'</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">'&amp;lt;'</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'&gt;'</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">'&amp;gt;'</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'"'</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">'&amp;quot;'</span></span><br><span class="line">            <span class="keyword">case</span> <span class="string">'&amp;'</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="string">'&amp;amp;'</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line">htmlEscape(<span class="built_in">String</span>().big()); <span class="comment">//"&amp;lt;big&amp;gt;&amp;lt;/big&amp;gt;"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>split()</li>
</ul>
<p><code>split()</code> 接收一个“分隔符”作为参数，将原字符串分解成多个子串，然后保存在一个数组中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'red,orange,yellow,green'</span>;</span><br><span class="line">str.split(<span class="string">','</span>); <span class="comment">//(4) ["red", "orange", "yellow", "green"]</span></span><br></pre></td></tr></table></figure>
<p>另外，这个“分隔符”还可以是一个正则对象，从而让 <code>split()</code> 方法根据正则的匹配结果来分解原字符串。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str.split(<span class="regexp">/[^\,]+/</span>); <span class="comment">//(5) ["", ",", ",", ",", ""]</span></span><br></pre></td></tr></table></figure>
<h3 id="字符串比较"><a href="#字符串比较" class="headerlink" title="字符串比较"></a>字符串比较</h3><ul>
<li>localeCompare()</li>
</ul>
<p><code>localeCompare</code> 方法会按照本地区的特殊性进行字符串的大小比较。<br>如果字符串对象大于接收的字符串参数，则返回 <code>1</code> 。<br>如果字符串对象小于接收的字符串参数，则返回 <code>-1</code>。<br>如果两个字符串完全相同，则返回 <code>0</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str1 = <span class="string">'abc'</span>;</span><br><span class="line"><span class="keyword">var</span> str2 = <span class="string">'ghi'</span>;</span><br><span class="line"><span class="keyword">var</span> string = <span class="string">'def'</span>;</span><br><span class="line"></span><br><span class="line">string.localeCompare(str1); <span class="comment">//1</span></span><br><span class="line">string.localeCompare(<span class="string">'def'</span>); <span class="comment">//0</span></span><br><span class="line">string.localeCompare(str2); <span class="comment">//-1</span></span><br></pre></td></tr></table></figure>
<h3 id="HTML-方法"><a href="#HTML-方法" class="headerlink" title="HTML 方法"></a>HTML 方法</h3><p>String 对象中提供了很多快速创建 HTML字符串的方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> s = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'Html String Test'</span>);</span><br><span class="line"></span><br><span class="line">s.big(); <span class="comment">//"&lt;big&gt;Html String Test&lt;/big&gt;"</span></span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th style="text-align:center">方法</th>
<th style="text-align:center">输出结果</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">anchor(name)</td>
<td style="text-align:center"><code>&lt;a name= &quot;name&quot;&gt;string&lt;/a&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">big()</td>
<td style="text-align:center"><code>&lt;big&gt;string&lt;/big&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">bold()</td>
<td style="text-align:center"><code>&lt;b&gt;string&lt;/b&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">fixed()</td>
<td style="text-align:center"><code>&lt;tt&gt;string&lt;/tt&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">italics()</td>
<td style="text-align:center"><code>&lt;i&gt;string&lt;/i&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">link(url)</td>
<td style="text-align:center"><code>&lt;a href=&quot;url&quot;&gt;string&lt;/a&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">small()</td>
<td style="text-align:center"><code>&lt;small&gt;string&lt;/small&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">strike()</td>
<td style="text-align:center"><code>&lt;strike&gt;string&lt;/strike&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">sub()</td>
<td style="text-align:center"><code>&lt;sub&gt;string&lt;/sub&gt;</code></td>
</tr>
<tr>
<td style="text-align:center">sup()</td>
<td style="text-align:center"><code>&lt;sup&gt;string&lt;/sup&gt;</code></td>
</tr>
</tbody>
</table>
<h2 id="静态方法"><a href="#静态方法" class="headerlink" title="静态方法"></a>静态方法</h2><ul>
<li>fromCharCode()</li>
</ul>
<p><code>fromCharCode</code> 是 <code>String</code> 对象的静态方法。接收一个或多个十进制的字符编码作为参数并返回这些编码对应的字符本身。<br>从功能上看 <code>fromCharCode</code> 方法与 String 实例对象的 <code>charCodeAt</code> 方法是相反的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>.fromCharCode(<span class="string">'h'</span>.charCodeAt(), <span class="string">'e'</span>.charCodeAt(), <span class="string">'l'</span>.charCodeAt(), <span class="string">'l'</span>.charCodeAt(), <span class="string">'o'</span>.charCodeAt());</span><br><span class="line"><span class="built_in">String</span>.fromCharCode(<span class="number">0x2300</span>); <span class="comment">//"⌀"</span></span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/23/professional-javascript-chapter-5-Boolean/" rel="next" title="《JavaScript 高级程序设计》第五章：Boolean">
                <i class="fa fa-chevron-left"></i> 《JavaScript 高级程序设计》第五章：Boolean
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/05/12/professional-javascript-chapter-5-single-object/" rel="prev" title="《JavaScript 高级程序设计》第五章：单体内置对象">
                《JavaScript 高级程序设计》第五章：单体内置对象 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#转换方法"><span class="nav-number">2.</span> <span class="nav-text">转换方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#String"><span class="nav-number">3.</span> <span class="nav-text">String()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例方法"><span class="nav-number">4.</span> <span class="nav-text">实例方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#字符与编码"><span class="nav-number">4.1.</span> <span class="nav-text">字符与编码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串操作"><span class="nav-number">4.2.</span> <span class="nav-text">字符串操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串截取"><span class="nav-number">4.3.</span> <span class="nav-text">字符串截取</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串位置"><span class="nav-number">4.4.</span> <span class="nav-text">字符串位置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串模式匹配方法"><span class="nav-number">4.5.</span> <span class="nav-text">字符串模式匹配方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串比较"><span class="nav-number">4.6.</span> <span class="nav-text">字符串比较</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HTML-方法"><span class="nav-number">4.7.</span> <span class="nav-text">HTML 方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#静态方法"><span class="nav-number">5.</span> <span class="nav-text">静态方法</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
